<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>


    <link href="css/base.css" rel="stylesheet">
    <link href="css/head.css" rel="stylesheet">

    <link href="css/car.css" rel="stylesheet">
</head>

<body>
    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/head.js"></script>
    <script src="js/Utils.js"></script>

    <script src="js/mock.js"></script>
    <script src="mock/car.js"></script>

    <div class="head"></div>
    <div class="nav_head"></div>

    <div class="main">
        <table>
            <thead>
                <th>商品名称</th>
                <th>商品价格</th>
                <th>商品数量</th>
                <th>操作</th>
            </thead>

            <tbody>

            </tbody>
        </table>

        <div class="total"></div>

        <div class="operation">

        </div>
    </div>
    <script>
        let user = hasLogin()
        let username
        let car_data
        let d;
        if (!user) {
            alert("请先登录")
            location.href = 'login.html'
            
        }

        username = user['username']
        data = {
            'username': username
        }

        data = JSON.stringify(data)

        $.ajax({
            data,
            url: baseUrl + 'get_cart.php',
            type: 'POST',
            success: function (res) {

                res = JSON.parse(res)

                if (res.code == 200) {
                    car_data = res.data
                    render(res.data)

                } else {
                    $('.main table').hide()
                }
            }
        })

        function render(data) {

            d = data.pet_list

            checkEmpty(d)

            $('.main table tbody').empty()
            $('.total').empty()
            $('.operation').empty()


            for (let i = 0; i < d.length; i++) {
                $('.main table tbody').append(`
                    <tr>
                        <td>
                            <img src="${baseUrl + d[i].image}">
                            <span>${d[i].pet_name}</span>
                        </td>
                        <td>${d[i].price}</td>
                        <td
                            <div class="numberBox">
                                <div class="sub" onclick="change_number(${d[i].id},${d[i].number-1},${d[i].stock},${i})">-</div>
                                <input class="number" type="text" onchange="diyNumber(${d[i].id}, ${d[i].stock}, ${i})" value="${d[i].number}">
                                <div class="add" onclick="change_number(${d[i].id},${d[i].number+1},${d[i].stock},${i})">+</div>
                            </div>
                        </td>
                        <td>
                            <div class="button" id="del" onclick=delPet('${d[i].id}')>删除</div>
                        </td>
                    </tr>
                `)

                $('.numberBox').eq(i)[0].index = i

            }

            $('.total').html(`
                <h2>合计:${data.totalPrice}</h2>
            `)

            $('.operation').append(`
                <div class="button" id="pay">结算</div>
                <div class="button" id="clearCar">清空购物车</div>
            `)

            initEvent()
        }

        function delPet(id) {
            
            let username = user.username

            data = {
                username,
                id
            }

            data = JSON.stringify(data)

            $.ajax({
                data,
                url: baseUrl + 'del_car.php',
                type: 'POST',
                success: function (res) {
                    
                    res = JSON.parse(res)
                    if (res.code == 200) {
                        alert("删除成功")
                        data = car_data['pet_list']

                        for (let i = 0; i < data.length; i++) {
                            if (data[i].id == id) {
                                d.splice(i, 1)
                                break
                            }
                        }
                        
                        render(car_data)

                    } else {
                        console.log("删除失败")
                    }
                }
            })
        }


        function initEvent() {
            clearCarEvent()
            payEvent()
        }

        function getTotalPrice(){
            let data = car_data['pet_list']

            for (let i = 0; i < data.length; i++) {
                            total += data[i].price * data[i].number
                        }

                        car_data.totalPrice = Number(total).toFixed(2)
        }

        //支付事件
        function payEvent() {
            let data = {
                username
            }
            data = JSON.stringify(data)
            $('#pay').click(function () {
                $.ajax({
                    data,
                    url: baseUrl + 'add_order.php',
                    type: 'POST',
                    success: function (res) {
                        if (typeof (res) == 'string') {
                            res = JSON.parse(res)
                        }

                        if (res.code == 200) {
                            
                            location.href = 'order_detail.html?order_number='+res.data['order_number']
                        } else {
                            alert(res.code)
                        }
                    }
                })
            })
        }

        //清空购物车事件
        function clearCarEvent() {
            let data = {
                username
            }

            data = JSON.stringify(data)

            $('#clearCar').click(function () {
                $.ajax({
                    data,
                    url: baseUrl + 'clear_cart.php',
                    type: 'POST',
                    success: function (res) {
                        res = JSON.parse(res)

                        if (res.code == 200) {
                            clearCar()
                            checkEmpty()
                        }
                    }
                })
            })
        }

        function diyNumber(id,stock,index){
            number = $('.numberBox').eq(index).children('.number')[0].value

            change_number(id, number, stock, index)
        }

        function change_number(id, number,stock,index){
            
            
            if(number < 0){
                number = $('.numberBox').eq(index).children('.number')[0].value = 0
                
            }

            if(number > stock){
                number = $('.numberBox').eq(index).children('.number')[0].value = stock
                
            }


            
            $('.numberBox').eq(index).children('.number')[0].value = number

            let username = user.username

            let data = {
                id,
                number,
                username
            }

            data = JSON.stringify(data)

            $.ajax({
                data,
                url : baseUrl + 'change_cart.php',
                type: 'POST',
                success: function(res){
                    if(typeof(res) == 'string'){
                        res = JSON.parse(res)
                    }

                    if(res.code == 200){
                        console.log("修改成功", number)
                        location.reload()
                    }else{
                        console.log("修改失败")
                    }
                }
            })
        }


        function clearCar() {
            d = []
        }

        function checkEmpty() {
            if (d.length == 0) {
                $(".main").empty()

                $(".main").html(`
                    <h2 style="text-align:center;">暂无任何商品</h2>
                `)
                return true
            }

            return false

        }


    </script>
</body>

</html>